'''
    Pegaso
    Copyright (c) 2012 Dario Tognacci

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

import getopt, sys, os
import loader
from structures import *
from util import *
import wrapper


if __name__ == '__main__':
    
    # Parameter
    print_xml = False
    xml_filename = None
    hdr_filename = None
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:", ["header=", "print-xml="])
    except:
        manage_error(None, usage)
    
    for opt, arg in opts:
        if opt in ("-h", "--header"):
            hdr_filename = arg
        if opt in ("--print-xml"):
            print_xml = True
            xml_filename = arg
    
    if hdr_filename is None:
        manage_error(IOError(), "input file not specified.")
    try:
        input_file = open(hdr_filename, "r")
    except IOError as e:
        manage_error(e,"input file not found.")
    
    print("Loading statements...")
    loader.load_statements_table(input_file)
    print("Statements table loaded.")
    
    # If uncommented, print the Statements Table as linked list.
    #print(statements_table)
    
    # Print XML
    if print_xml:
        try:
            xml = open(arg, "w")
            print("<definitions>", file=xml)
            for e in statements_table:
                print(statements_table[e].get_xml_representation(), file=xml)
            print("</definitions>", file=xml)
            xml.close()
        except IOError as e:
            manage_error(e, "cannot create the xml file.")
    
    # Creation of the .x file.
    try:
        basename = os.path.splitext(hdr_filename)[0]
        xdr_header_file = open(basename + ".x", "w")
    except IOError as e:
        manage_error(e, "cannot create the {0}.x file.".format(basename))
    
    ### LOCAL & REMOTE ###
    # Write the XDR representation of every statement presents in the
    # statements_table.
    for key in statements_table:
        statement = statements_table[key]
        try:
            if isinstance(statement,SimpleType) or isinstance(statement, StructType):
                xdr_header_file.write(statement.get_xdr_local_representation() + "\n")
                xdr_header_file.write(statement.get_xdr_remote_representation() + "\n")
            else:
                 xdr_header_file.write(statement.get_xdr_representation() + "\n")
        except IOError as e:
             manage_error(e, "cannot write the XDR statement definition ({0})".format(
                     statement))
    
    # XDR structures that group function parameters. 
    for key in function_table:
        function = function_table[key]
        param_struct = ["struct R_{0}_Param {{".format(function['identifier'])]
        param_struct.append("\t{0} return_value;".format("REMOTE_" + function['return_type']))
        for parameter in function['parameters']:
            if isinstance(parameter, ParameterType):
                if parameter.trasform_ptr:
                    new_type = parameter.trasform_ptr.type
                    param_struct.append("\t{0} {1}<>;".format("REMOTE_" + new_type,parameter.identifier))
                else:
                    param_struct.append("\t{0} {1};".format(("REMOTE_" + parameter.type),
                                                      parameter.identifier))
        param_struct.append("};")
        try:
            xdr_header_file.write("\n".join(param_struct) + "\n")
        except IOError as e:
            manage_error(e, "cannot write XDR strutcture for function {0}.".format(
                     function['identifier']))
    
    # Program definition.
    program_infos = ["program {0}_PROGRAM {{".format(basename)]
    program_infos.append("\tversion {0}_VERSION {{".format(basename))
    
    # Definitions of methods.
    i = 1
    for key in function_table:
        function = function_table[key]
        program_infos.append("\tR_{0}_Param R_{1}(R_{2}_Param) = {3};".format(
                             function['identifier'], function['identifier'],
                              function['identifier'], i))
        i = i+1

    program_infos.append("\t}} = {0};".format(version))
    program_infos.append("} = 0x2000000;")
    
    try:
        xdr_header_file.write("\n".join(program_infos))
        xdr_header_file.close()
    except IOError as e:
        manage_error(e, "cannot write program definition.")
    
    print("XDR header created.")
    
    # Client file
    try:
        client_file = TabWriter(open("{0}_client.c".format(basename), "w"))
    except IOError as e:
        manage_error(e, "cannot create {0}_client.c file.".format(basename))
    
    for key in function_table:
        function = function_table[key]
        f_repr = wrapper.create_client_function(function)
        client_file.write(f_repr)
        client_file.write(['\n'])
    
    client_file.close()
    print("Wrap Client file created.")
    
    # Server file
    try:
        server_file = TabWriter(open("{0}_server.c".format(basename), "w"))
    except IOError as e:
        manage_error(e, "cannot create {0}_server.c file.".format(basename))
    
    for key in function_table:
        function = function_table[key]
        f_repr = wrapper.create_server_function(function)
        server_file.write(f_repr)
        server_file.write(['\n'])
    
    client_file.close()
    print("Wrap Server file created.")
    
    print("OPERATION COMPLETED!")
